<!--
  查：
    1：定义接口api
    2:导入api
    3:进入页面调用api
    4:调用成功：存储并渲染
    5：与分页建立关联
       a:总条数存储并与分页组件关联
       b:页码与页容量与接口请求参数关联
       c:页码或者页容量改变都要请求接口

  删：
    1：点击删除弹出确认框
    2：定义导入与调用删除api
    3:调用成功
        a:提示
        b:刷新列表（考虑分页：如果当前页只有一条数据 && 页码>1  页码-- 再刷新）

   员工导出
   1：拿到所有员工数据
   2：通过excel导出方法导出

  分配角色(没有新增弹框的修改)
    1:创建分配角色弹框组件
    2：导入注册使用
    3：点击分配角色打开弹框
    4：完成布局（需要调用接口获取列表渲染）
    5：回显数据
       a：当前点击项包含弹框显示数据（深拷贝）
       b：当前点击项不包含弹框显示数据（调用接口）
    6:定义导入与调用分配角色接口
    7：调用成功
       a:关闭弹框
       b:清空表单数据与验证
       c:提示
       d:是否刷新父级列表（父级有展示相应数据就刷新）

 -->

<template>
  <div class="employees">
    <el-card>
      <div class="top">
        <div class="left">
          <i class="el-icon-info" />
          <span>共{{ total }}条记录</span>
        </div>
        <div class="right">
          <el-button
            size="small"
            type="danger"
            @click="outputExcel"
          >简单表头导出</el-button>
          <el-button size="small" type="info">复杂表头导出</el-button>
          <el-button
            size="small"
            type="success"
            @click="$router.push('/employees/import')"
          >excel导入</el-button>
          <el-button
            v-if="checkPermission('employees_add_btn')"
            size="small"
            type="primary"
            @click="addEvent"
          >新增员工</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="bottom">
      <el-table :data="list">
        <el-table-column label="序号">
          <template v-slot="{ $index }">
            <div>
              {{ (page.page - 1) * page.size + $index + 1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="姓名" sortable />
        <el-table-column prop="staffPhoto" label="头像">
          <template v-slot="{ row }">
            <img
              v-imgerror
              class="avatar"
              :src="row.staffPhoto"
              alt=""
              @click="imgClick(row.staffPhoto)"
            >
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" sortable />
        <el-table-column prop="workNumber" label="工号" sortable />
        <el-table-column prop="formOfEmployment" label="聘用形式" sortable>
          <template #default="{ row }">
            <div v-formatVal:hireType="row.formOfEmployment" />
          </template>
        </el-table-column>
        <el-table-column prop="departmentName" label="部门" sortable />
        <el-table-column prop="timeOfEntry" label="入职时间" sortable />
        <el-table-column prop="enableState" label="帐户状态" sortable>
          <template v-slot="{ row }">
            <div v-formatVal:workingState="row.enableState" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="{ row }">
            <div v-if="false">{{ row }}</div>
            <!-- 路由传值
                1：query
                    this.$router.push('/xxx?参数名=值')
                    this.$route.query.参数名
                2:动态路由匹配
                    {path:'/xxx/:id'}
                    this.$router.push('/xxx/值')
                    this.$route.params.id
                3：parmas传值
                  this.$router.push({
                    name:'..',
                    params:{
                      参数名:值
                    }
                  })
                  this.$route.params.参数名
          -->

            <el-button
              type="text"
              @click="$router.push('/employees/detail/' + row.id)"
            >查看</el-button>
            <el-button type="text">转正</el-button>
            <el-button type="text">调岗</el-button>
            <el-button type="text">离职</el-button>
            <el-button type="text" @click="roleEvent(row)">角色</el-button>
            <el-button type="text" @click="delEvent(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <!-- @size-change="handleSizeChange"
          @current-change="handleCurrentChange" -->
        <el-pagination
          :current-page.sync="page.page"
          :page-sizes="[1, 3, 5, 10, 100, 200, 300, 400]"
          :page-size.sync="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="sizeChange"
          @current-change="getData"
        />
      </div>
    </el-card>
    <!-- 新增弹框组件 -->
    <Add ref="add" @getData="getData" />
    <!-- 二维码弹框 -->
    <UserCode ref="code" />
    <!-- 分配角色弹框 -->
    <Role ref="role" />
  </div>
</template>
<script>
import { sysUser, sysUserDelete } from '@/api/employees'
import { changeEnur } from '@/api/constant/employees'
import jsCookie from 'js-cookie'
import Add from './components/add.vue'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import UserCode from './components/userCode'
import Role from './components/role.vue'
export default {
  components: {
    Add,
    UserCode,
    Role
  },
  data() {
    return {
      changeEnur,
      list: [],
      page: {
        page: 1,
        size: +jsCookie.get('employees_size') || 10
      },
      total: 400
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await sysUser(this.page)
      this.list = res.data.rows
      this.total = res.data.total
      console.log(res)
    },
    // 聘用形式转换
    formatterEmployment(row, column, value, index) {
      return changeEnur('hireType', value)
    },
    // 帐户状态
    formatterState(row, column, value, index) {
      return changeEnur('workingState', value)
    },
    // 页容量改变
    sizeChange() {
      jsCookie.set('employees_size', this.page.size)
      this.getData()
    },
    // 新增按钮点击
    addEvent() {
      this.$refs.add.show = true
    },
    // 删除
    async delEvent(id) {
      await this.$confirm('您确定删除该员工吗?', '温馨提示')
      await sysUserDelete(id)
      this.$message.success('删除成功')
      if (this.list.length === 1 && this.page.page > 1) {
        this.page.page--
      }
      this.getData()
    },
    // 员工导出
    async outputExcel() {
      // 拿到所有数据
      const res = await sysUser({
        page: 1,
        size: 99999999999
      })
      console.log(res.data.rows)
      const newArr = res.data.rows.map((item) => {
        return [
          item.username,
          item.staffPhoto,
          item.mobile,
          item.workNumber,
          changeEnur('hireType', item.formOfEmployment),
          item.departmentName,
          item.timeOfEntry
        ]
      })
      export_json_to_excel({
        filename: '员工列表',
        header: [
          '姓名',
          '头像',
          '手机号',
          '工号',
          '聘用形式',
          '部门',
          '入职时间'
        ],
        data: newArr
      })
    },
    // 员工头像点击
    async imgClick(imgUrl) {
      if (!imgUrl) {
        this.$message.error('无头像地址！')
        return
      }
      this.$refs.code.showCode = true
      // 打开弹框同时，传入头像地址且生成二维码，
      await this.$nextTick()
      this.$refs.code.createCode(imgUrl)
    },
    // 角色点击事件
    roleEvent(row) {
      this.$refs.role.show = true
      this.$refs.role.getUserInfo(row.id)
      console.log(row)
    }
  }
}
</script>
<style lang="scss" scoped>
.employees {
  padding: 20px;
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .left {
      background-color: #e6f7ff;
      border: 1px solid #a5ddff;
      padding: 8px;
      border-radius: 6px;
      i {
        color: #409eff;
        margin-right: 5px;
      }
    }
  }
  .bottom {
    margin-top: 20px;
  }
  .page {
    text-align: center;
    padding-top: 20px;
  }
  .avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }
}
</style>
